#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    long long minOperationsToMakeMedianK(vector<int>& nums, int k) {
        int n = nums.size();
        if (n == 1)return abs(nums[0] - k);
        int l = -1;
        int r = n;
        long long ans = 0;
        sort(nums.begin(), nums.end());
        if (n == 2) {
            if (nums[0] >= k)return (long long)nums[0] + nums[1] - 2 * k;
            else if (nums[1] <= k)return k - nums[1];
            else return nums[1] - k;
        }
        while (l + 1 != r) {
            int mid = (l + r) / 2;
            if (nums[mid] >= k)r = mid;
            else l = mid;
        }
        // cout<<r<<endl;

        if (k > nums[n - 1])r = n - 1;
        if (r == n / 2) {
            return abs(nums[r] - k);
        }
        if (r > n / 2) {
            for (int i = r; i >= n / 2; i--) {
                if (nums[i] < k) {
                    ans += k - nums[i];
                }
            }
            return ans;
        }
        else if (r < n / 2) {
            for (int i = r; i <= n / 2; i++) {
                if (nums[i] > k) {
                    ans += nums[i] - k;
                }
            }
            return ans;
        }

        return ans;
    }
};